<?php
class systemModel extends RPHP_Model
{

    protected $_auth = null;

    //检查权限
    public function checkPriv($pv, $return = true)
    {
        $auth = $this->auth->CheckPriv($pv, $return);
        if ($return) {
            $this->_auth = $auth;
        }

        return $auth;
    }

    //检查帐号是否被占用
    public function checkUsername($usr, $type = 0, $r = 0)
    {
        $n = array('电子邮箱', '手机号码');
        if ($usr != '') {
            $do = false;
            if ($type == 0) {
                if (preg_match("/^([_a-zA-Z0-9]+([\._a-zA-Z0-9-]+)*)@([a-z0-9-]{1,}(\.[a-z0-9-]{2,})*\.[a-z]{2,3})$/", $usr)) {
                    $where = " `email`='" . $usr . "'";
                    $do    = true;
                }
            } elseif ($type == 1) {
                if (preg_match("/^(13|14|15|17|18)([0-9]{9})$/", $usr)) {
                    $where = " `mobile`='" . $usr . "'";
                    $do    = true;
                }
            }

            if ($do) {

                $rs = $this->sql("SELECT COUNT(`aid`) AS cnt FROM {$this->_prefix['primary']}admin_account WHERE " . $where);
                if ($rs[0]['cnt'] < 1) {
                    if ($r) {
                        return true;
                    } else {
                        return '<span class="text-success">' . $n[$type] . '可以使用，请继续</span>';
                    }

                } else {
                    if ($r) {
                        return false;
                    } else {
                        return '<span class="text-danger">' . $n[$type] . '已经被使用，请重新选择</span>';
                    }

                }

            }
        } else {
            if ($r) {
                return false;
            } else {
                return '<span class="text-danger">' . $n[$type] . '不能为空</span>';
            }

        }

    }

    //保存用户
    public function saveUser($da, $aid = 0)
    {

        $code     = 900;
        $password = md5($da['password']);
        $stat     = intval($da['stat']);
        $groupid  = intval($da['groupid']);
        $uid      = intval($da['puid']);
        if (is_array($da['PRIVS'])) {
            $privs = implode(",", $da['PRIVS']);
        } else {
            $privs = "NON";
        }

        //修改管理员
        if ($aid > 0) {

            $sql = "SELECT `aid`,`pass_rand` FROM {$this->_prefix['primary']}admin_account WHERE `aid`=" . intval($aid) . " AND `stat`<3 AND `groupid`!=88";
            $rs  = $this->sql($sql);

            if ($rs) {

                if ($da['password'] != "") {
                    $pwd = ",`password`='" . md5($password . $rs[0]['pass_rand']) . "'";
                }

                $sql = "UPDATE {$this->_prefix['primary']}admin_account SET `uid`=" . $uid . ",`stat`=" . $stat . ",`groupid`=" . $groupid . ",`privs`='" . $privs . "'" . $pwd . ",`last_aid`=" . $this->_auth['aid'] . ",`last_edit`=" . $_SERVER['REQUEST_TIME'] . " WHERE `aid`=" . $rs[0]['aid'];
                $rd  = $this->sql($sql);
                if ($rd > 0) {
                    $code = 200;
                } else {
                    $code = 403;
                }

            } else {
                $code = 407;
            }

        }
        //新增管理员
        else {
            if ($da['email'] != "" && $da['mobile'] != "" && $da['password'] != "") {

                if ($this->CheckUsername($da['email'], 0, 1) && $this->CheckUsername($da['mobile'], 1, 1)) {

                    $pass_rand      = rand(100000, 999999);
                    $password       = md5(md5($da['password']) . $pass_rand);
                    $da['realname'] = addslashes(htmlspecialchars(trim($da['realname'])));

                    $sql = "INSERT INTO {$this->_prefix['primary']}admin_account (`email`,`mobile`,`realname`,`password`,`pass_rand`,`create_time`,`stat`,`groupid`,`privs`,`last_aid`,`last_edit`,`uid`) VALUES
                    ('" . $da['email'] . "','" . $da['mobile'] . "','" . $da['realname'] . "','" . $password . "','" . $pass_rand . "'," . $_SERVER['REQUEST_TIME'] . "," . $stat . "," . $groupid . ",'" . $privs . "'," . $this->_auth['aid'] . "," . $_SERVER['REQUEST_TIME'] . "," . $uid . ")";

                    $rd = $this->sql($sql);

                    if ($rd > 0) {
                        $code = 200;
                    } else {
                        $code = 403;
                    }

                } else {
                    $code = 601;
                }
            }
        }
        return $code;

    }

    //获取权限
    public function getChgpriv($groupid = 0, $privs)
    {
        $sql = "SELECT * FROM {$this->_prefix['primary']}admin_group WHERE `groupid` = " . intval($groupid) . " AND `groupid`!=88 LIMIT 1";
        $rs  = $this->sql($sql);
        if ($rs) {
            //开始组权限的显示
            if ($privs) {
                $priv_scope = explode(",", $rs[0]['privs']);
                $br         = 6;
                $i          = 0;
                $n          = 0;
                foreach ($privs['model'] as $k => $r) {
                    if (in_array($k, $priv_scope)) {
                        //在权限范围内才显示出来
                        if ($n > 0) {
                            $html .= '<div style="float:left;width:100%;border-bottom:1px dashed #333; height:10px; margin-bottom:10px;"></div>';
                        }

                        $html .= '<div style="float:left;width:100%;"><input type="checkbox" name="CKALL[]" id="ck' . $n . '" value="' . $k . '" onclick="prvskall(this)" /> <label for="ck' . $n . '"><strong>' . $r[0] . '</strong></label></div>';
                        foreach ($privs['privs'][$k] as $j => $s) {
                            $i++;

                            $nowpriv = $k . '_' . $s[1];

                            $html .= '<div style="float:left;width:33%;"><input type="checkbox" id="pr' . $i . '" name="PRIVS[]" onclick="prvskpart(\'' . $k . '\')" value="' . $nowpriv . '"' . $chk . ' /> <label for="pr' . $i . '">' . $s[0] . '</label></div>';

                        }

                        $n++;
                    }
                }
                return $html;
            }
        } else {
            return '组不存在';
        }
    }

    //获取权限
    public function getChgprivEdit($groupid = 0, $ygpid = 0, $aid = 0, $privs)
    {
        $sql = "SELECT * FROM {$this->_prefix['primary']}admin_group WHERE `groupid` = " . intval($groupid) . " AND `groupid`!=88 LIMIT 1";
        $rs  = $this->sql($sql);
        if ($rs) {
            $usrpriv = array();
            $dochk   = false;
            $allchk  = '';
            //判断是否改变了组
            if ($groupid == intval($ygpid)) {
                //获取用户权限
                $sql     = "SELECT `privs` FROM {$this->_prefix['primary']}admin_account WHERE `aid` = " . intval($aid) . " AND `groupid`!=88 LIMIT 1";
                $usr     = $this->sql($sql);
                $usrpriv = explode(",", $usr[0]['privs']);
                $dochk   = true;
                $allchk  = '';
            }

            //开始组权限的显示
            if ($privs) {
                $priv_scope = explode(",", $rs[0]['privs']);
                $br         = 6;
                $i          = 0;
                $n          = 0;
                foreach ($privs['model'] as $k => $r) {
                    if (in_array($k, $priv_scope)) {
                        //在权限范围内才显示出来
                        if ($n > 0) {
                            $html .= '<div style="float:left;width:100%;border-bottom:1px dashed #333; height:10px; margin-bottom:10px;"></div>';
                        }

                        $html .= '<div style="float:left;width:100%;"><input type="checkbox" name="CKALL[]" id="ck' . $n . '" value="' . $k . '" onclick="prvskall(this)" /> <label for="ck' . $n . '"><strong>' . $r[0] . '</strong></label></div>';
                        if ($privs['privs'][$k]) {
                            foreach ($privs['privs'][$k] as $j => $s) {
                                $i++;

                                $nowpriv = $k . '_' . $s[1];

                                if ($dochk) {
                                    if (in_array($nowpriv, $usrpriv)) {
                                        $chk = ' checked';
                                    } else {
                                        $chk = '';
                                    }

                                } else {
                                    $chk = '';
                                }

                                $html .= '<div style="float:left;width:33%;"><input type="checkbox" id="pr' . $i . '" name="PRIVS[]"' . $chk . ' onclick="prvskpart(\'' . $k . '\')" value="' . $nowpriv . '"' . $chk . ' /> <label for="pr' . $i . '">' . $s[0] . '</label></div>';

                            }
                        }
                        $n++;
                    }
                }
                return $html;
            }
        } else {
            return '组不存在';
        }
    }

    //获取管理员数据
    public function getUsers($aid = 0)
    {
        if (intval($aid) > 0) {
            $where = " AND `aid`=" . intval($aid);
        }

        $sql  = "SELECT `aid`,`email`,`mobile`,`realname`,`groupid`,left(`privs`,3) AS `pv`,`create_time`,`stat`,`last_aid`,`last_edit`,`uid` FROM {$this->_prefix['primary']}admin_account WHERE `stat`<3 " . $where . " ORDER BY `groupid` DESC";
        $data = $this->sql($sql);

        if ($data) {

            if ($aid > 0) {
                return $data[0];
            } else {

                foreach ($data as $r) {
                    if ($r['uid'] > 0) {
                        $uids[] = $r['uid'];
                    }
                }

                if ($uids) {
                    $sql = "SELECT `uid`,`name`,`mobile` FROM {$this->_prefix['primary']}member_account WHERE `uid` IN (" . implode(",", $uids) . ")";
                    $tmp = $this->sql($sql);
                    if ($tmp) {
                        foreach ($tmp as $r) {
                            $user[$r['uid']] = $r;
                        }
                    }
                }

                return array(
                    'data' => $data,
                    'user' => $user,
                );
            }

        }

    }

    //获取组信息
    public function getGroups($groupid = 0, $non = false)
    {
        if ($groupid > 0) {
            if ($non) {
                $where = " WHERE `groupid`!=" . intval($groupid);
            } else {
                $where = " WHERE `groupid`=" . intval($groupid);
            }

        }
        $sql = "SELECT * FROM {$this->_prefix['primary']}admin_group" . $where . " ORDER BY `groupid` ASC";
        if ($groupid > 0 && !$non) {
            return $this->db->getrow($sql);
        } else {
            return $this->sql($sql);
        }

    }

    //保存组
    public function saveGroup($da, $groupid = 0)
    {

        $code = 900;
        $name = addslashes(htmlspecialchars(trim($da['name'])));
        if (is_array($da['PRIVS'])) {
            $privs = implode(",", $da['PRIVS']);
        } else {
            $privs = "";
        }

        $groupid = intval($groupid);
        //修改
        if ($groupid > 0) {

            $group = $this->getGroups($groupid);
            if ($group) {
                $groups      = $this->getGroups($groupid, true);
                $name_exists = false;
                foreach ($groups as $r) {
                    if ($r['name'] == $name) {
                        $name_exists = true;
                    }

                }

                if (!$name_exists) {

                    $sql = "UPDATE {$this->_prefix['primary']}admin_group SET `name`='" . $name . "',`privs`='" . $privs . "',`last_aid`=" . $this->_auth['aid'] . ",`last_edit`=" . $_SERVER['REQUEST_TIME'] . " WHERE `groupid`=" . $groupid;

                    $rs = $this->sql($sql);
                    if ($rs > 0) {
                        $code = 200;
                    } else {
                        $code = 403;
                    }

                } else {
                    $code = 650;
                }

            } else {
                $code = 404;
            }

        }
        //新增
        else {

            $groups      = $this->getGroups();
            $name_exists = false;
            foreach ($groups as $r) {
                if ($r['name'] == $name) {
                    $name_exists = true;
                }

            }

            if (!$name_exists) {

                $sql = "INSERT INTO {$this->_prefix['primary']}admin_group
                (`name`,`privs`,`last_aid`,`last_edit`) VALUES ('" . $name . "','" . $privs . "'," . $this->_auth['aid'] . "," . $_SERVER['REQUEST_TIME'] . ")";

                $rs = $this->sql($sql);
                if ($rs > 0) {
                    $code = 200;
                } else {
                    $code = 403;
                }

            } else {
                $code = 650;
            }

        }
        return $code;

    }

    //获取AID用户名
    public function getAdminUsername($aid)
    {
        //判断是否数组或者单个数字
        if (is_array($aid)) {
            $where = " IN (" . implode(",", $aid) . ")";
        } elseif (is_numeric($aid)) {
            $where = "=" . intval($aid);
        }

        $sql = "SELECT `aid`,`realname` FROM {$this->_prefix['primary']}admin_account WHERE `aid`" . $where;
        $rs  = $this->sql($sql);
        if ($rs) {
            foreach ($rs as $r) {
                $AID[$r['aid']] = $r['realname'];
            }
            return $AID;
        }
        return false;
    }

    //获取AID在线信息
    public function getOnline($aid)
    {
        if (is_array($aid)) {

            $lastact_time = $_SERVER['REQUEST_TIME'] - 900; //15分钟以内有操作为在线

            $sql = "SELECT `aid`,MAX(`lastact_time`) AS `acttime` FROM {$this->_prefix['primary']}admin_online WHERE `aid` IN (" . implode(",", $aid) . ") AND `lastact_time`>=" . $lastact_time . " GROUP BY `aid`";
            $rs  = $this->sql($sql);
            if ($rs) {
                foreach ($rs as $r) {
                    $AID[$r['aid']] = $r['acttime'];
                }
                return $AID;
            }
        }
        return false;
    }

    //获取AID最后登录信息
    public function getSignedLog($aid)
    {
        if (is_array($aid)) {

            $sql = "SELECT `aid`,MAX(`log_time`) AS `logtime` FROM {$this->_prefix['primary']}admin_signinlog WHERE `aid` IN (" . implode(",", $aid) . ") GROUP BY `aid`";
            $rs  = $this->sql($sql);
            if ($rs) {
                foreach ($rs as $r) {
                    $AID[$r['aid']] = $r['logtime'];
                }
                return $AID;
            }
        }
        return false;
    }

}
